package marchsoft.modules.selfFish.pisciculture.service.impl;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import marchsoft.exception.BadRequestException;
import marchsoft.modules.selfFish.pisciculture.entity.Knowledge;
import marchsoft.modules.selfFish.pisciculture.entity.dto.KnowledgeDto;
import marchsoft.modules.selfFish.pisciculture.entity.vo.KnowledgeVo;
import marchsoft.modules.selfFish.pisciculture.mapper.KnowledgeMapper;
import marchsoft.modules.selfFish.pisciculture.service.KnowledgeService;
import marchsoft.response.Result;
import marchsoft.utils.FileUtils;
import marchsoft.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 *@title KnowledgeServiceImpl
 *@description
 *@author Lenovo
 *@version 1.0
 *@create 2024-07-15 17:23
 */
@Service
@Slf4j
public class KnowledgeServiceImpl extends ServiceImpl<KnowledgeMapper, Knowledge>implements KnowledgeService {

    @Autowired
    private KnowledgeMapper KnowledgeMapper;

    @Autowired
    private KnowledgeService KnowledgeService;

    @Override
    public Result<Object> getKnowledgeList(String content, Long pageNum, Long pageSize) {
        return Result.success(KnowledgeMapper.getKnowledgeList(new Page<>(pageNum, pageSize),content));
    }

    @Override
    public Result<Object> create(KnowledgeDto KnowledgeDto) {
        Knowledge Knowledge = new Knowledge();
        BeanUtils.copyProperties(KnowledgeDto,Knowledge);
        Knowledge.setCreatedUserId(SecurityUtils.getCurrentUserId());
        Knowledge.setCreatedTime(LocalDateTime.now());
        if(KnowledgeMapper.insert(Knowledge)>0){
            log.info(StrUtil.format("【添加养鱼知识库成功】操作人id：{}，新增目标Knowledget：{}", SecurityUtils.getCurrentUserId(), KnowledgeDto));
            return Result.success("新增成功！");
        };
        return Result.error("新增失败！");
    }

    @Override
    public Result<Object> delete(Set<Long> ids) {
        UpdateWrapper<Knowledge> uw = new UpdateWrapper<>();
        uw.in("id",ids)
                .set("status",false);
        if(KnowledgeService.update(uw)){
            log.info(StrUtil.format("【删除养鱼知识库成功】操作人id：{}，删除目标Knowledgets：{}", SecurityUtils.getCurrentUserId(), ids.toString()));
            return Result.success("删除成功！");
        };
        return Result.error("删除失败！");
    }

    @Override
    public Result<Object> update(KnowledgeDto knowledgeDto) {
        Knowledge Knowledge = getById(knowledgeDto.getId());
        if (ObjectUtil.isEmpty(Knowledge)) {
            log.error(StrUtil.format("【修改养鱼知识库失败】操作人id：{}，修改目标Knowledge为空，目标KnowledgeId：{}", SecurityUtils.getCurrentUserId(), knowledgeDto.getId()));
            throw new BadRequestException("修改失败，当前数据id不存在");
        }
        if(Knowledge.getCreatedUserId()!=SecurityUtils.getCurrentUserId()){
            log.error(StrUtil.format("【修改养鱼知识库失败】操作人id：{}，目标Knowledge新增人id：{}", SecurityUtils.getCurrentUserId(), Knowledge.getCreatedUserId()));
            throw new BadRequestException("该养鱼知识库不是你新增的，不能修改：" + Knowledge.getTitle());
        }
        BeanUtils.copyProperties(knowledgeDto,Knowledge);
        if(updateById(Knowledge)){
            log.info(StrUtil.format("【修改养鱼知识库成功】操作人id：{}，修改目标Knowledge：{}", SecurityUtils.getCurrentUserId(), knowledgeDto));
            return Result.success("修改成功！");
        };
        return Result.error("修改失败！");
    }

    @Override
    public void download(String content, HttpServletResponse response) throws IOException {
        Page page = new Page<>(-1, -1);
        List<KnowledgeVo> records = KnowledgeMapper.getKnowledgeList(page, content).getRecords();
        List<Map<String, Object>> list = new ArrayList<>();
        records.forEach(KnowledgetVo -> {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("标题", KnowledgetVo.getTitle());
            map.put("内容", KnowledgetVo.getContent());
            map.put("创建时间", LocalDateTimeUtil.format(KnowledgetVo.getCreatedTime(), DatePattern.NORM_DATETIME_FORMATTER));
            list.add(map);
        });
        Map<Integer, Integer>widthMap = new HashMap<>();
        FileUtils.downloadExcel(list,widthMap, response);
    }
}
